package com.gzhryc.shared_device.oem.h5.mng;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.DateBranchHelper;
import com.gzhryc.shared_device.base.enums.EPayState;
import com.gzhryc.shared_device.base.enums.EPayType;
import com.gzhryc.shared_device.base.enums.ERefundState;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNOrder;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNShopOrder;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyBattery;
import com.gzhryc.shared_device.bxscn.code.dao.enums.BXSCNShopOrderEnum;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNOrderService;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNShopOrderService;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryService;
import com.gzhryc.shared_device.bxscn.code.services.dto.BXSCNOrderSearch;
import com.gzhryc.shared_device.bxscn.code.services.dto.BXSCNShopOrderSearch;
import com.gzhryc.shared_device.bxscn.code.services.dto.PortableEnergyBatterySearch;
import com.gzhryc.shared_device.cdb.code.services.CDBOrderService;
import com.gzhryc.shared_device.cdcz.code.services.CDCZOrderService;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.dao.db.DeviceTypeFunc;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeFuncService;
import com.gzhryc.shared_device.common.device.services.dto.DeviceSearch;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayOrder;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayAbnormalPayOrder;
import com.gzhryc.shared_device.common.payment.dao.db.WXRefundOrder;
import com.gzhryc.shared_device.common.payment.services.WXPayOrderService;
import com.gzhryc.shared_device.common.payment.services.WXPayAbnormalPayOrderService;
import com.gzhryc.shared_device.common.payment.services.WXRefundOrderService;
import com.gzhryc.shared_device.common.payment.services.dto.WXPayAbnormalPayOrderSearch;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.pcl.code.services.PCLOrderService;

public class DataRecoveryUtils {

    static Logger log = Logger.getLogger(DataRecoveryUtils.class);

    /**
     * 修复便携式电池序列号中间的空格，V0.1.8
     * 1. 修复电池对象
     * 2. 修复电池租借订单
     * 3. 修复会员租借订单
     */
    public static void BXSCNBatteryFixSpaces(){
        //修复电池对象
        Integer pageNo = 1;
        Integer pageLimit  = 100;

        PortableEnergyBatterySearch batterySearch = new PortableEnergyBatterySearch();
        List<PortableEnergyBattery> portableEnergyBatteryList = PortableEnergyBatteryService.self().findBySearch(batterySearch,pageNo,pageLimit);
        while(portableEnergyBatteryList != null && portableEnergyBatteryList.size() > 0){
            for(PortableEnergyBattery portableBattery : portableEnergyBatteryList){
                String deviceSn = new String(portableBattery.getDeviceSn());
                if(deviceSn.contains(" ") || deviceSn.contains("-")) {
                    log.info("修复便携式电池序列号中间的空格和横线，序列号：{{0}}",deviceSn);
                    deviceSn = deviceSn.replace(" ", "");
                    deviceSn = deviceSn.replace("-", "");
                    try {
						PortableEnergyBatteryService.self().updateDeviceSn(deviceSn,portableBattery.getDeviceSn());
					} catch (LogicException e) {
						log.error(e.getMessage(), e);
					}
                }
            }
            pageNo = pageNo + 1;
            portableEnergyBatteryList = PortableEnergyBatteryService.self().findBySearch(batterySearch,pageNo,pageLimit);
        }

        List<DateBranchHelper.DateBranchItem> branchItemList = DateBranchHelper.self().getYearDateBranchItems();
        //修复订单
        for(DateBranchHelper.DateBranchItem branchItem : branchItemList){
            BXSCNShopOrderService bxscnShopOrderService = BXSCNShopOrderService.self(branchItem.getDate());
            MemberBusinessOrderService memberBusinessOrderService = MemberBusinessOrderService.self(branchItem.getDate());

            pageNo = 1;
            BXSCNShopOrderSearch search = new BXSCNShopOrderSearch();
            List<BXSCNShopOrder> bxscnShopOrderList = bxscnShopOrderService.findBySearch(search,pageNo,pageLimit);
            while(bxscnShopOrderList != null && bxscnShopOrderList.size() > 0){
                for(BXSCNShopOrder bxscnShopOrder : bxscnShopOrderList){
                    if(StringTools.isNotBlank(bxscnShopOrder.getPortableBatterySn())) {
                        String deviceSn = new String(bxscnShopOrder.getPortableBatterySn());
                        if(deviceSn.contains(" ") || deviceSn.contains("-")) {
                            log.info("修复订单中便携式电池序列号中间的空格，序列号：{{0}}，订单号：{{1}}", deviceSn, bxscnShopOrder.getTradeNo());
                            deviceSn = deviceSn.replace(" ", "");
                            deviceSn = deviceSn.replace("-", "");
                            bxscnShopOrderService.forceUpdatePortableBatterySn(bxscnShopOrder.getTradeNo(), deviceSn);
                            memberBusinessOrderService.updateDeviceSn(bxscnShopOrder.getTradeNo(),bxscnShopOrder.getBatteryTypeName(), deviceSn);
                        }
                    }
                    //修复订单金额
                    if(BXSCNShopOrderEnum.PayState.PaySuccess.index().equals(bxscnShopOrder.getPayState())){
                        if(BXSCNShopOrderEnum.State.WaitLease.index().equals(bxscnShopOrder.getState())
                            || BXSCNShopOrderEnum.State.LeaseTimeout.index().equals(bxscnShopOrder.getState())
                            || BXSCNShopOrderEnum.State.RevertFinish.index().equals(bxscnShopOrder.getState()) ){
                            //获取支付订单
                            List<WXPayOrder> payOrderList = WXPayOrderService.self(bxscnShopOrder.getCreateDate()).findByBusinessTradeNo(bxscnShopOrder.getTradeNo());
                            if(payOrderList != null && payOrderList.size() > 0){
                                Integer payMoney = 0;
                                for(WXPayOrder payOrder : payOrderList){
                                    if(EPayState.Success.index().equals(payOrder.getPayStatus())){
                                        payMoney = payMoney + payOrder.getReceiptMoney();
                                    }
                                }
                                List<WXRefundOrder> refundOrderList = WXRefundOrderService.self(bxscnShopOrder.getCreateDate()).findByBusinessTradeNo(bxscnShopOrder.getTradeNo());
                                if(refundOrderList != null && refundOrderList.size() > 0){
                                    for(WXRefundOrder refundOrder : refundOrderList){
                                        if(ERefundState.Success.index().equals(refundOrder.getRefundStatus())){
                                            payMoney = payMoney - refundOrder.getRefundMoney();
                                        }
                                    }
                                }

                                if(payMoney < 0){
                                    payMoney = 0;
                                }

                                Long money = NumberTools.changeMoneyLi(NumberTools.changeMoney(payMoney));
                                if(bxscnShopOrder.getMoney() != money || bxscnShopOrder.getPayMoney() != payMoney) {
                                    log.info("修复订单中金额，订单号：{{0}}", bxscnShopOrder.getTradeNo());
                                    bxscnShopOrderService.forceUpdateMoney(bxscnShopOrder.getTradeNo(), money, payMoney);
                                    memberBusinessOrderService.forceUpdateMoney(bxscnShopOrder.getTradeNo(), money, payMoney);
                                }
                            }
                        }
                    }

                }
                pageNo = pageNo + 1;
                bxscnShopOrderList = bxscnShopOrderService.findBySearch(search,pageNo,pageLimit);
            }
        }
    }

    /**
     * 修复便携式电池门店租借订单，撤销订单时金额没有清零，V0.1.8
     */
    public static void BXSCNBatteryOrderCancel() {
        List<DateBranchHelper.DateBranchItem> branchItemList = DateBranchHelper.self().getYearDateBranchItems();
        //修复订单
        for (DateBranchHelper.DateBranchItem branchItem : branchItemList) {
            BXSCNShopOrderService bxscnShopOrderService = BXSCNShopOrderService.self(branchItem.getDate());
            MemberBusinessOrderService memberBusinessOrderService = MemberBusinessOrderService.self(branchItem.getDate());

            Integer pageNo = 1;
            Integer pageLimit = 100;
            BXSCNShopOrderSearch search = new BXSCNShopOrderSearch();
            search.setPayState(BXSCNShopOrderEnum.PayState.Cancel.index());
            List<BXSCNShopOrder> bxscnShopOrderList = bxscnShopOrderService.findBySearch(search, pageNo, pageLimit);
            while (bxscnShopOrderList != null && bxscnShopOrderList.size() > 0) {
                for (BXSCNShopOrder bxscnShopOrder : bxscnShopOrderList) {
                    if (bxscnShopOrder.getMoney() > 0 || bxscnShopOrder.getPayMoney() > 0) {
                        log.info("修复撤销订单中金额，订单号：{{0}}", bxscnShopOrder.getTradeNo());
                        bxscnShopOrderService.forceUpdateMoney(bxscnShopOrder.getTradeNo(), 0L, 0);
                        memberBusinessOrderService.forceUpdateMoney(bxscnShopOrder.getTradeNo(), 0L, 0);
                    }
                }
                pageNo = pageNo + 1;
                bxscnShopOrderList = bxscnShopOrderService.findBySearch(search, pageNo, pageLimit);
            }
        }
    }

    public static void BXSCNOrderFinish() {
        List<DateBranchHelper.DateBranchItem> branchItemList = DateBranchHelper.self().getYearDateBranchItems();
        //修复订单
        for (DateBranchHelper.DateBranchItem branchItem : branchItemList) {
            BXSCNShopOrderService bxscnShopOrderService = BXSCNShopOrderService.self(branchItem.getDate());
            BXSCNOrderService bxscnOrderService = BXSCNOrderService.self(branchItem.getDate());
            MemberBusinessOrderService memberBusinessOrderService = MemberBusinessOrderService.self(branchItem.getDate());

            Integer pageNo = 1;
            Integer pageLimit = 100;
            BXSCNShopOrderSearch search = new BXSCNShopOrderSearch();
            search.setPayState(BXSCNShopOrderEnum.PayState.PaySuccess.index());
            List<BXSCNShopOrder> bxscnShopOrderList = bxscnShopOrderService.findBySearch(search, pageNo, pageLimit);
            while (bxscnShopOrderList != null && bxscnShopOrderList.size() > 0) {
                for (BXSCNShopOrder bxscnShopOrder : bxscnShopOrderList) {
                    if(EPayType.WXPay.index().equals(bxscnShopOrder.getPayType())) {
                        List<WXPayOrder> payOrderList = WXPayOrderService.self(bxscnShopOrder.getCreateDate()).findByBusinessTradeNo(bxscnShopOrder.getTradeNo());
                        Integer payMoney = 0;
                        if(payOrderList != null) {
                            for (WXPayOrder wxPayOrder : payOrderList) {
                                if (EPayState.Success.index().equals(wxPayOrder.getPayStatus())) {
                                    payMoney = payMoney + wxPayOrder.getReceiptMoney();
                                }
                            }
                        }
                        Integer refundMoney = 0;
                        List<WXRefundOrder> refundOrderLlist = WXRefundOrderService.self(bxscnShopOrder.getCreateDate()).findByBusinessTradeNo(bxscnShopOrder.getTradeNo());
                        if(refundOrderLlist != null) {
                            for (WXRefundOrder refundOrder : refundOrderLlist) {
                                if (ERefundState.Success.index().equals(refundOrder.getRefundStatus())) {
                                    refundMoney = refundMoney + refundOrder.getRefundMoney();
                                }
                            }
                        }

                        payMoney = payMoney - refundMoney;

                        if (payMoney > 0 && !payMoney.equals(bxscnShopOrder.getPayMoney())) {
                            log.info("修复完成订单中金额，订单号：{{0}}", bxscnShopOrder.getTradeNo());
                            Long money = NumberTools.changeMoneyLi(NumberTools.changeMoney(payMoney));
                            bxscnShopOrderService.forceUpdateMoney(bxscnShopOrder.getTradeNo(), money, payMoney);
                            memberBusinessOrderService.forceUpdateMoney(bxscnShopOrder.getTradeNo(), money, payMoney);
                        }
                    }
                }
                pageNo = pageNo + 1;
                bxscnShopOrderList = bxscnShopOrderService.findBySearch(search, pageNo, pageLimit);
            }

            pageNo = 1;
            BXSCNOrderSearch search1 = new BXSCNOrderSearch();
            search.setPayState(BXSCNShopOrderEnum.PayState.PaySuccess.index());
            List<BXSCNOrder> bxscnOrderList = bxscnOrderService.findBySearch(search1, pageNo, pageLimit);
            while (bxscnOrderList != null && bxscnOrderList.size() > 0) {
                for (BXSCNOrder bxscnOrder : bxscnOrderList) {
                    if(EPayType.WXPay.index().equals(bxscnOrder.getPayType())) {
                        List<WXPayOrder> payOrderList = WXPayOrderService.self(bxscnOrder.getCreateDate()).findByBusinessTradeNo(bxscnOrder.getTradeNo());
                        Integer payMoney = 0;
                        if(payOrderList != null) {
                            for (WXPayOrder wxPayOrder : payOrderList) {
                                if (EPayState.Success.index().equals(wxPayOrder.getPayStatus())) {
                                    payMoney = payMoney + wxPayOrder.getReceiptMoney();
                                }
                            }
                        }
                        Integer refundMoney = 0;
                        List<WXRefundOrder> refundOrderLlist = WXRefundOrderService.self(bxscnOrder.getCreateDate()).findByBusinessTradeNo(bxscnOrder.getTradeNo());
                        if(refundOrderLlist != null) {
                            for (WXRefundOrder refundOrder : refundOrderLlist) {
                                if (ERefundState.Success.index().equals(refundOrder.getRefundStatus())) {
                                    refundMoney = refundMoney + refundOrder.getRefundMoney();
                                }
                            }
                        }

                        payMoney = payMoney - refundMoney;

                        if (payMoney > 0 && !payMoney.equals(bxscnOrder.getPayMoney())) {
                            log.info("修复完成订单中金额，订单号：{{0}}", bxscnOrder.getTradeNo());
                            Long money = NumberTools.changeMoneyLi(NumberTools.changeMoney(payMoney));
                            bxscnOrderService.forceUpdateMoney(bxscnOrder.getTradeNo(), money, payMoney);
                            memberBusinessOrderService.forceUpdateMoney(bxscnOrder.getTradeNo(), money, payMoney);
                        }
                    }
                }
                pageNo = pageNo + 1;
                bxscnOrderList = bxscnOrderService.findBySearch(search1, pageNo, pageLimit);
            }
        }
    }

    public static void deviceFuncInfo(){
        Integer pageNo = 1;
        Integer pageLimit = 100;
        Map<String, List<DeviceTypeFunc>> deviceTypeFuncMap = new HashMap<>();
        DeviceSearch search = new DeviceSearch();
        List<Device> deviceList = DeviceService.self().findBySearch(search,pageNo,pageLimit);
        while (deviceList != null && deviceList.size() > 0 ) {
            for (Device device : deviceList) {
                List<DeviceTypeFunc> deviceTypeFuncList = deviceTypeFuncMap.get(device.getDeviceTypeId());
                if (deviceTypeFuncList == null) {
                    deviceTypeFuncList = DeviceTypeFuncService.self().findByTypeId(device.getDeviceTypeId());
                    if (deviceTypeFuncList != null && deviceTypeFuncList.size() > 0) {
                        deviceTypeFuncMap.put(device.getDeviceTypeId(), deviceTypeFuncList);
                    } else {
                        log.error("设备类型：{{0}}未找到功能项", device.getDeviceTypeId());
                        continue;
                    }
                }

                String deviceFunCodes = "";
                String deviceFunNames = "";
                for (DeviceTypeFunc deviceTypeFunc : deviceTypeFuncList) {
                    deviceFunCodes = deviceFunCodes + "," + deviceTypeFunc.getCode();
                    deviceFunNames = deviceFunNames + "," + deviceTypeFunc.getCodeName();
                }

                Device updateEntity = new Device();
                updateEntity.setDeviceSn(device.getDeviceSn());
                updateEntity.setDeviceFunCodes(deviceFunCodes.substring(1));
                updateEntity.setDeviceFunNames(deviceFunNames.substring(1));

                try {
                    DeviceService.self().updateNotNull(updateEntity);
                } catch (LogicException e) {
                    log.error(e.getMessage(), e);
                }
            }
            pageNo = pageNo + 1;
            deviceList = DeviceService.self().findBySearch(search,pageNo,pageLimit);
        }
    }

    public static void orderSetAgentId(){
        Integer pageNo = 1;
        Integer pageLimit = 100;
        PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
        List<DateBranchHelper.DateBranchItem> branchItemList = DateBranchHelper.self().getYearDateBranchItems();
        List<PlacePhysicalStore> physicalStoreList = PlacePhysicalStoreService.self().findJoinBySearch(search,pageNo,pageLimit);
        while (physicalStoreList != null && physicalStoreList.size() > 0) {
            for(PlacePhysicalStore physicalStore : physicalStoreList) {
                log.info("修改{{0}}网点{{1}}代理的订单",physicalStore.getId(),physicalStore.getUserId());
                //修复订单
                for (DateBranchHelper.DateBranchItem branchItem : branchItemList) {
                    BXSCNShopOrderService bxscnShopOrderService = BXSCNShopOrderService.self(branchItem.getDate());
                    BXSCNOrderService bxscnOrderService = BXSCNOrderService.self(branchItem.getDate());
                    CDBOrderService cdbOrderService = CDBOrderService.self(branchItem.getDate());
                    CDCZOrderService cdczOrderService = CDCZOrderService.self(branchItem.getDate());
                    PCLOrderService pclOrderService = PCLOrderService.self(branchItem.getDate());
                    MemberBusinessOrderService memberBusinessOrderService = MemberBusinessOrderService.self(branchItem.getDate());

                    bxscnShopOrderService.updateAgentIdByPlaceId(physicalStore.getId(),physicalStore.getUserId());
                    bxscnOrderService.updateAgentIdByPlaceId(physicalStore.getId(),physicalStore.getUserId());
                    cdbOrderService.updateAgentIdByPlaceId(physicalStore.getId(),physicalStore.getUserId());
                    cdczOrderService.updateAgentIdByPlaceId(physicalStore.getId(),physicalStore.getUserId());
                    pclOrderService.updateAgentIdByPlaceId(physicalStore.getId(),physicalStore.getUserId());
                    memberBusinessOrderService.updateAgentIdByPlaceId(physicalStore.getId(),physicalStore.getUserId());

                    bxscnShopOrderService.updateRevertAgentIdByPlaceId(physicalStore.getId(),physicalStore.getUserId());
                    bxscnOrderService.updateRevertAgentIdByPlaceId(physicalStore.getId(),physicalStore.getUserId());
                    cdbOrderService.updateRevertAgentIdByPlaceId(physicalStore.getId(),physicalStore.getUserId());
                }
            }
            pageNo = pageNo + 1;
            physicalStoreList = PlacePhysicalStoreService.self().findJoinBySearch(search,pageNo,pageLimit);
        }

    }

    public static void checkWXPayTimeout() {
        Integer pageNo = 1;
        Integer pageLimit = 100;
        WXPayAbnormalPayOrderSearch search = new WXPayAbnormalPayOrderSearch();
        List<WXPayAbnormalPayOrder> timeoutPayOrderList = WXPayAbnormalPayOrderService.self().findBySearch(search, pageNo, pageLimit);
        while (timeoutPayOrderList != null && timeoutPayOrderList.size() > 0) {
            for (WXPayAbnormalPayOrder timeoutPayOrder : timeoutPayOrderList) {
                try {
                    WXPayAbnormalPayOrderService.self().checkToDelete(timeoutPayOrder);
                } catch (LogicException e) {
                    //
                }
            }
            pageNo = pageNo + 1;
            timeoutPayOrderList = WXPayAbnormalPayOrderService.self().findBySearch(search, pageNo, pageLimit);
        }
    }
}
